# -*- coding: utf-8 -*-
import requests
import time
import datetime
import json
from .models import *
from bs4 import BeautifulSoup
import random

def get_last_dlt_data():
    # {'code': '2020023', 'red': [4, 5, 20, 21, 30, 13], 'blue': [1,2], 'date': '2020-04-12'}
    URL = 'https://www.lottery.gov.cn/historykj/history.jspx?page=false&_ltype=dlt&termNum=50&startTerm=&endTerm='
    contents = requests.get(URL)
    content = contents.content.decode('utf-8')
    contents.close()
    soup = BeautifulSoup(content,features='html.parser')
    col = soup.find_all('tr')
    col = col[2]
    col1 = col.find_all('td',class_='red')
    red_list = []
    for c1 in col1:
        red_list.append(int(c1.get_text()))
    col2 = col.find_all('td',class_='blue')
    blue_list = []
    for c2 in col2:
        blue_list.append(int(c2.get_text()))
    result = {}
    result['red'] = red_list
    result['blue'] = blue_list
    result['code'] = col.find_all('td')[0].get_text()
    result['date'] = col.find_all('td')[-1].get_text()
    return result

def get_last_pl3_data():
    # {'code': '2020023', 'red': [4, 5, 3,], 'date': '2020-04-12'}
    URL = 'https://www.lottery.gov.cn/historykj/history.jspx?page=false&_ltype=pls&termNum=50&startTerm=&endTerm='
    contents = requests.get(URL)
    content = contents.content.decode('utf-8')
    contents.close()
    soup = BeautifulSoup(content,features='html.parser')
    col = soup.find_all('tr')
    col = col[2]
    col1 = col.find_all('td')[1].get_text()
    result = {}
    result['red'] = list(map(int, col1.split()))
    result['code'] = col.find_all('td')[0].get_text()
    result['date'] = col.find_all('td')[-1].get_text()
    return result

def get_last_pl5_data():
    # {'code': '2020023', 'red': [4, 5, 1,3,4], 'date': '2020-04-12'}
    URL = 'https://www.lottery.gov.cn/historykj/history.jspx?page=false&_ltype=plw&termNum=50&startTerm=&endTerm='
    contents = requests.get(URL)
    content = contents.content.decode('utf-8')
    contents.close()
    soup = BeautifulSoup(content,features='html.parser')
    col = soup.find_all('tr')
    col = col[2]
    col1 = col.find_all('td')[1].get_text()
    result = {}
    result['red'] = list(map(int, col1.split()))
    result['code'] = col.find_all('td')[0].get_text()
    result['date'] = col.find_all('td')[-1].get_text()
    return result

def get_last_qixincai_data():
     # {'code': '2020023', 'red': [4, 5, 2,3,8,7,1], 'date': '2020-04-12'}
    URL = 'https://www.lottery.gov.cn/historykj/history.jspx?page=false&_ltype=qxc&termNum=50&startTerm=&endTerm='
    contents = requests.get(URL)
    content = contents.content.decode('utf-8')
    contents.close()
    soup = BeautifulSoup(content,features='html.parser')
    col = soup.find_all('tr')
    col = col[2]
    col1 = col.find_all('td')[1].get_text()
    result = {}
    col2 = []
    for c in col1:
        col2.append(int(c))
    result['red'] = col2
    result['code'] = col.find_all('td')[0].get_text()
    result['date'] = col.find_all('td')[-1].get_text()
    return result

def get_last50_ssq_data():
    # 返回json 50期的数据
    # 先从http://www.cwl.gov.cn/kjxx/ssq/kjgg/ 获取cookie
    # API http://www.cwl.gov.cn/cwl_admin/kjxx/findDrawNotice?name=ssq&issueCount=50
    r_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 \
        (KHTML, like Gecko) Chrome/77.0.3865.10 Safari/537.36','Referer': 'http://www.cwl.gov.cn/kjxx/ssq/kjgg/'}
    URL_main = 'http://www.cwl.gov.cn/kjxx/ssq/kjgg/'
    URL_api = 'http://www.cwl.gov.cn/cwl_admin/kjxx/findDrawNotice?name=ssq&issueCount=50'
    Connect = requests.session()
    Connect.get(URL_main, headers = r_headers)
    Request_msg = Connect.get(URL_api, headers = r_headers)
    request_json_data = json.loads(Request_msg.content)
    Connect.close()
    return request_json_data

def get_last_ssq_data():
    # 获取最新的一期 
    # 格式为{'code': '2020023', 'red': [4, 5, 20, 21, 30, 33], 'blue': 8, 'date': '2020-04-12(日)'}
    request_json_data = get_last50_ssq_data()
    last_code = {}
    s = request_json_data['result'][0]
    last_code['code'] = s['code']
    last_code['red'] = list(map(int, s['red'].split(',')))
    last_code['blue'] = int(s['blue'])
    last_code['date'] = s['date']
    return last_code

def get_last50_3d_data():
    # 返回json 50期的数据
    r_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 \
        (KHTML, like Gecko) Chrome/77.0.3865.10 Safari/537.36','Referer': 'http://www.cwl.gov.cn/kjxx/fc3d/kjgg/'}
    URL_main = 'http://www.cwl.gov.cn/kjxx/fc3d/kjgg/'
    URL_api = 'http://www.cwl.gov.cn/cwl_admin/kjxx/findDrawNotice?name=3d&issueCount=50'
    Connect = requests.session()
    Connect.get(URL_main, headers = r_headers)
    Request_msg = Connect.get(URL_api, headers = r_headers)
    request_json_data = json.loads(Request_msg.content)
    Connect.close()
    return request_json_data

def get_last_3d_data():
    # 获取最新的一期 
    request_json_data = get_last50_3d_data()
    last_code = {}
    s = request_json_data['result'][0]
    last_code['code'] = s['code']
    last_code['red'] = list(map(int, s['red'].split(',')))
    last_code['date'] = s['date']
    return last_code

def get_last50_qilecai_data():
    # 返回json 50期的数据
    r_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 \
        (KHTML, like Gecko) Chrome/77.0.3865.10 Safari/537.36','Referer': 'http://www.cwl.gov.cn/kjxx/qlc/kjgg/'}
    URL_main = 'http://www.cwl.gov.cn/kjxx/qlc/kjgg/'
    URL_api = 'http://www.cwl.gov.cn/cwl_admin/kjxx/findDrawNotice?name=qlc&issueCount=50'
    Connect = requests.session()
    Connect.get(URL_main, headers = r_headers)
    Request_msg = Connect.get(URL_api, headers = r_headers)
    request_json_data = json.loads(Request_msg.content)
    Connect.close()
    return request_json_data

def get_last_qilecai_data():
    # 获取最新的一期 
    request_json_data = get_last50_qilecai_data()
    last_code = {}
    s = request_json_data['result'][0]
    last_code['code'] = s['code']
    last_code['red'] = list(map(int, s['red'].split(',')))
    last_code['blue'] = int(s['blue'])
    last_code['date'] = s['date']
    return last_code


def alg_ssq_001(last_code, foreignKeyID):
    # 双色球算法00
    # {'code': '2020023', 'red': [4, 5, 20, 21, 30, 33], 'blue': 8, 'date': '2020-04-12(日)'}
    
    # 篮球
    blue_one = int(last_code['blue'])
    pre_date = last_code['code']
    kill_blue = []
    # 
    blue_total_list = list(range(1,17))
    blue_sum = int(blue_one) + 6
    if blue_sum > 16:
        blue_sum = blue_sum - 16
    for b in blue_total_list:
        if str(blue_sum)[-1] == str(b)[-1]:
            blue_total_list.remove(b)
            if b not in kill_blue:
                kill_blue.append(b)    
    # 
    blue_sum = int(blue_one) + 10
    if blue_sum > 16:
        blue_sum = blue_sum - 16
    for b in blue_total_list:
        if str(blue_sum)[-1] == str(b)[-1]:
            blue_total_list.remove(b)
            if b not in kill_blue:
                kill_blue.append(b)
    # 
    blue_sum = int(blue_one) - 7
    for b in blue_total_list:
        if str(blue_sum)[-1] == str(b)[-1]:
            blue_total_list.remove(b)
            if b not in kill_blue:
                kill_blue.append(b)
    #
    b = datetime.datetime.now().month
    if b in blue_total_list:
        blue_total_list.remove(b)
        if b not in kill_blue:
                kill_blue.append(b)
    #
    blue_sum = int(str(pre_date)[-1]) + 1
    for b in blue_total_list:
        if str(blue_sum)[-1] == str(b)[-1]:
            blue_total_list.remove(b)
            if b not in kill_blue:
                kill_blue.append(b)
    kill_blue.sort()

    # 红球
    kill_red = []
    red_total_list = list(range(1,34))

    # 末尾两数相除:除取三位数最后一位
    abc = float(last_code['red'][-1] / last_code['red'][-2])
    abc = str(abc).replace('.','')[:3][-1]
    for b in red_total_list:
        if abc == str(b)[-1]:
            red_total_list.remove(b)
            if b not in kill_red:
                kill_red.append(b)
    kill_red.sort()

    kill_blue = list(set(kill_blue))
    kill_red = list(set(kill_red))
    result = {'kill':{'red':kill_red,'blue':kill_blue},}
    red = []
    for n in range(1, 34):
        if n not in kill_red:
            red.append(n)
    blue = []
    for n in range(1,17):
        if n not in kill_blue:
            blue.append(n)
    result['will'] = {'red':red,'blue':blue}

    s = Alg_everyone()
    s.link_id = foreignKeyID
    s.alg_data = json.dumps(result)
    s.alg_name = "规律选号"
    s.save()

def alg_ssq_002(last_code, foreignKeyID):
    # 双色球算法002
    # {'code': '2020023', 'red': [4, 5, 20, 21, 30, 33], 'blue': 8, 'date': '2020-04-12(日)'}
    pass

def alg_3d_001(last_code, foreignKeyID):
    # 3d算法
    # {'code': '2020023', 'red': [4, 5, 8], 'date': '2020-04-12(日)'}
    pass

def alg_qlc_001(last_code, foreignKeyID):
    # 七乐彩算法1
    # {'code': '2020023', 'red': [4, 5, 20, 21, 30, 13,23], 'blue': 8, 'date': '2020-04-12(日)'}
    pass

def alg_dlt_001(last_code, foreignKeyID):
    # 大乐透
    # # {'code': '2020023', 'red': [4, 5, 20, 21, 30, 33], 'blue': [1,2], 'date': '2020-04-12'}
    pass

def alg_pl3_001(last_code, foreignKeyID):
    # 排列3
    # {'code': '2020023', 'red': [4, 5, 5,], 'date': '2020-04-12'}
    pass

def alg_pl5_001(last_code, foreignKeyID):
    # 排列5
    # # {'code': '2020023', 'red': [4, 5, 4,1,12], 'date': '2020-04-12'}
    pass

def alg_qixincai_001(last_code, foreignKeyID):
    # 七星彩
    # {'code': '2020023', 'red': [4, 5, 2,3,8,7,1], 'date': '2020-04-12'}
    pass